﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NVelocity;
using NVelocity.Context;
using NVelocity.Runtime;
using NVelocity.Runtime.Visitor;
using NVelocity.Runtime.Resource.Loader;

namespace Com.Common.Cms
{
    public class NVelocityHelper
    {
        private NVelocity.App.VelocityEngine nvelocity = new NVelocity.App.VelocityEngine();
        private NVelocity.Context.IContext context = new NVelocity.VelocityContext();
        public NVelocityHelper()
        {
            Initializtion(null);
        }
        public NVelocityHelper(String templateFolder) {
            Initializtion(templateFolder);
        }
        public NVelocityHelper(Commons.Collections.ExtendedProperties properties)
        {
            nvelocity.Init(properties);
        }
        public NVelocityHelper Put(string key, object value)
        {
            context.Put(key, value);
            return this;
        }
        public NVelocityHelper Remove(string key)
        {
            context.Remove(key);
            return this;
        }

        public String Merge(string templateFileName)
        {
            System.IO.TextWriter writer = new System.IO.StringWriter();
            bool isSuccess = nvelocity.MergeTemplate(templateFileName, "UTF-8", context, writer);
            if (isSuccess)
            {
                return writer.ToString();
            }
            else
            {
                throw new Exception("合并模版是发生异常!");
            }
        }
        public String Merge(string templateFileName, String encodingName)
        {
            System.IO.TextWriter writer = new System.IO.StringWriter();
            bool isSuccess = nvelocity.MergeTemplate(templateFileName, encodingName, context, writer);
            if (isSuccess)
            {
                return writer.ToString();
            }
            else
            {
                throw new Exception("合并模版是发生异常!");
            }
        }
        public String Merge(string templateFileName, System.Text.Encoding encoding)
        {
            System.IO.TextWriter writer = new System.IO.StringWriter();
            bool isSuccess = nvelocity.MergeTemplate(templateFileName, encoding.EncodingName, context, writer);
            if (isSuccess)
            {
                return writer.ToString();
            }
            else
            {
                throw new Exception("合并模版是发生异常!");
            }
        }
        public bool SaveFile(string templateFileName, string saveFolder, string fileName)
        {
            saveFolder = ProcessFilePath(saveFolder);
            if (!System.IO.Directory.Exists(saveFolder))
            {
                System.IO.Directory.CreateDirectory(saveFolder);
            }
            System.IO.File.WriteAllText(saveFolder + fileName, this.Merge(templateFileName),System.Text.Encoding.UTF8);
            return true;
        }
        public bool SaveFile(string templateFileName, string saveFolder, string fileName,System.Text.Encoding encoding)
        {
            if(string.IsNullOrEmpty(templateFileName)){
                throw new Exception("模板文件名为空!");
            }
           if(string.IsNullOrEmpty(saveFolder)){
                throw new Exception("文件保存路径字符串为null");
            }
            if(string.IsNullOrEmpty(fileName)){
                throw new Exception("文件名字符串为null");
            }
            if (!System.IO.Directory.Exists(saveFolder))
            {
                System.IO.Directory.CreateDirectory(saveFolder);
            }
   
            encoding = encoding == null ? System.Text.Encoding.Default : encoding;
            System.IO.File.WriteAllText(saveFolder + fileName, this.Merge(templateFileName), encoding);
            return true;
        }
        private void Initializtion(string templateFolder)
        {
            templateFolder = templateFolder ?? "./templates/";
            Commons.Collections.ExtendedProperties properties = new Commons.Collections.ExtendedProperties();
            properties.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            properties.AddProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8");
            properties.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "false");
            properties.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateFolder);
            properties.AddProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
            properties.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
            properties.AddProperty(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, "20");
            nvelocity.Init(properties);
        }
        /// <summary>
        /// 处理路径字符串
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private String ProcessFilePath(String path)
        {
            var pattern = @"(.+?)(?=[/\\]*$)";
            var matche = System.Text.RegularExpressions.Regex.Match(path, pattern);
            return matche.Value + @"\";
        }
    }
}
